<?php
abstract class Common
{
  public static $db;
  public static $queries;

  public static function init()
  {
    // Open database connection.
    self::$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    // Load predefined queries.
    $queriesXml = simplexml_load_file($_SERVER["DOCUMENT_ROOT"] . '/manage/db/queries.xml');

    self::$queries = array();

    foreach($queriesXml as $query)
      self::$queries[(string)$query['name']] = (string)$query;
  }

  public static function query($name, $parameters = array())
  {
    if (!isset(self::$queries[$name]))
      throw new Exception("Undefined query: $name");

    $sql = self::$queries[$name];

    if (count($parameters))
    {
      $formattedParams = array();

      // Prepend a ':' to each parameter name and escape the value properly.
      foreach($parameters as $paramName => $paramValue)
      {
        if (!is_numeric($paramValue))
        {
          if (is_null($paramValue))
            $paramValue = 'NULL';
          else
            $paramValue = "'".self::$db->real_escape_string($paramValue)."'";
        }

        $formattedParams[":$paramName"] = $paramValue;
      }

      // Replace placeholders in the query with assigned values.
      $sql = strtr($sql, $formattedParams);
    }

    // Display the query if SHOWSQL is true (for debugging purposes).
    if (defined('SHOWSQL') && SHOWSQL)
      echo htmlentities($sql)."<br />\n";

    // Execute the query and return the result.
    return self::$db->query($sql);
  }
}

?>